import tushare as ts
import numpy as np
import pandas as pd
import time
from others.money163 import money163
import datetime
#神奇公式实现
def main():
         money = money163()
         pro = ts.pro_api(token='936d1029be68a59a3e77eeb9e4eb1ea3c36502bd4b4bf9e1aae91bd8')
         df = pro.stock_basic(exchang='',list_status='L',fields='ts_code,symbol,name,area,industry,list_date')
         df2= pd.DataFrame(columns=['ts_code','symbol','name','area','industry','list_date'])
         #报告期
         start_date=(datetime.datetime.now() - datetime.timedelta(weeks=8)).strftime("%Y%m%d")
         end_date=time.strftime('%Y%m%d' , time.localtime())
         #datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day#'20220112'
         ts_df = pd.DataFrame(columns=['name','roc','yield_ratio','roc_ranked','yr_ranked','sum_rank'])
         for i in range(0,len(df)):
             print(i)
             #time.sleep(10)
             if df.iloc[i]['industry'] not in [u'银行',u'保险']:
                 #if i>10:
                 #    break
                 ts_code = df.iloc[i]['ts_code']
                 #当前市值
                 daily_basic = pro.daily_basic(ts_code=ts_code,trade_date=end_date,fields='ts_code,total_mv')
                 mkt_val=0
                 if len(daily_basic)==0:
                     print(('connot get %s')% (ts_code))
                     continue
                 else :
                     mkt_val = daily_basic.iloc[-1]['total_mv']
                 #利润表
                 income = money.lrb(ts_code[0:6])
                 if income is None :
                     continue
                     #pro.income(ts_code=ts_code,
                     #                start_date=start_date,
                     #                end_date=end_date,
                     #                fields='ts_code,ann_date,end_date,report_type,basic_eps,ebit')
                 #lrb(ts_code)
                 ebit = 0 if income.iloc[-1]['ebit'] is None else income.iloc[-1]['ebit'] #息税前利润
                 #息税前利润＝利润总额＋利息支出＝税前利润＋利息支出＝净利润＋所得税＋利息支出
                 #资产负债表
                 balancesheet =money.zcfzb(ts_code[0:6])
                 if balancesheet is None :
                     continue
                     #pro.balancesheet(ts_code=ts_code,
                     #                           start_date=start_date,
                     #                           end_date=end_date,
                     #                           fields='ts_code,fix_assets,accounts_receiv,notes_receiv,oth_receiv,prepayment,inventories,lt_eqt_invest,invest_real_estate,acct_payable,adv_receipts,payroll_payable,taxes_payable,oth_payable,acc_exp,deferred_inc,oth_cur_liab,minority_int,oth_eqt_tools,st_borr,lt_borr,non_cur_liab_due_1y,bond_payable,int_payable')
                 #计算资本支出
                 fix_assets =0 if balancesheet.iloc[-1]['fix_assets'] is None else balancesheet.iloc[-1]['fix_assets']#固定资产
                 acct_payable = 0 if balancesheet.iloc[-1]['acct_payable'] is None else balancesheet.iloc[-1]['acct_payable']#应付账款
                 adv_receipts = 0 if balancesheet.iloc[-1]['adv_receipts'] is None else balancesheet.iloc[-1]['adv_receipts']#预收款项
                 payroll_payable = 0 if balancesheet.iloc[-1]['payroll_payable'] is None else balancesheet.iloc[-1]['payroll_payable']#	应付职工薪酬
                 taxes_payable = 0 if balancesheet.iloc[-1]['taxes_payable'] is None else balancesheet.iloc[-1]['taxes_payable']#应交税费
                 oth_payable = 0 if balancesheet.iloc[-1]['oth_payable'] is None else balancesheet.iloc[-1]['oth_payable']#其他应付款
                 acc_exp = 0 if balancesheet.iloc[-1]['acc_exp'] is None else balancesheet.iloc[-1]['acc_exp']#预提费用
                 deferred_inc = 0 if balancesheet.iloc[-1]['deferred_inc'] is None else balancesheet.iloc[-1]['deferred_inc']#递延收益
                 oth_cur_liab = 0 if balancesheet.iloc[-1]['oth_cur_liab'] is None else balancesheet.iloc[-1]['oth_cur_liab']#其他流动负债


                 #accounts_receiv = 0 if balancesheet.iloc[-1]['accounts_receiv'] is None else balancesheet.iloc[-1]['accounts_receiv']#应收票据及应收账款

                 yspj = 0 if balancesheet.iloc[-1]['yspj'] is None else balancesheet.iloc[-1]['yspj']
                 yszk = 0 if balancesheet.iloc[-1]['yszk'] is None else balancesheet.iloc[-1]['yszk']
                 accounts_receiv=yspj+yszk


                 oth_receiv = 0 if balancesheet.iloc[-1]['oth_receiv'] is None else balancesheet.iloc[-1]['oth_receiv']#其他应收款
                 prepayment = 0 if balancesheet.iloc[-1]['prepayment'] is None else balancesheet.iloc[-1]['prepayment']#预付款项
                 inventories = 0 if balancesheet.iloc[-1]['inventories'] is None else balancesheet.iloc[-1]['inventories']#存货
                 lt_eqt_invest = 0 if balancesheet.iloc[-1]['lt_eqt_invest'] is None else balancesheet.iloc[-1]['lt_eqt_invest']#长期股权投资
                 invest_real_estate = 0 if balancesheet.iloc[-1]['invest_real_estate'] is None else balancesheet.iloc[-1]['invest_real_estate']#投资性房地产
                 minority_int = 0 if balancesheet.iloc[-1]['minority_int'] is None else balancesheet.iloc[-1]['minority_int']#少数股东权益
                 #oth_eqt_tools = 0 if balancesheet.iloc[-1]['oth_eqt_tools'] is None else balancesheet.iloc[-1]['oth_eqt_tools']#其他权益工具
                 st_borr = 0 if balancesheet.iloc[-1]['st_borr'] is None else balancesheet.iloc[-1]['st_borr']#短期借款
                 lt_borr = 0 if balancesheet.iloc[-1]['lt_borr'] is None else balancesheet.iloc[-1]['lt_borr']#长期借款
                 non_cur_liab_due_1y = 0 if balancesheet.iloc[-1]['non_cur_liab_due_1y'] is None else balancesheet.iloc[-1]['non_cur_liab_due_1y']#一年内到期的非流动负债
                 bond_payable = 0 if balancesheet.iloc[-1]['bond_payable'] is None else balancesheet.iloc[-1]['bond_payable']#应付债券
                 int_payable = 0 if balancesheet.iloc[-1]['int_payable'] is None else balancesheet.iloc[-1]['int_payable']#应付利息


                 non_int_cur_liability = acct_payable+ \
                                         adv_receipts+ \
                                         payroll_payable+ \
                                         taxes_payable+ \
                                         oth_payable+ \
                                         acc_exp+ \
                                         deferred_inc + \
                                         oth_cur_liab
                 nwc = accounts_receiv+ \
                       oth_receiv + \
                       prepayment + \
                       inventories + \
                       lt_eqt_invest + \
                       invest_real_estate - \
                       non_int_cur_liability
                 magic_cap = fix_assets + nwc

                 #计算有息负债  #oth_eqt_tools + \
                 total_int_liab = minority_int+ \
                                  st_borr + \
                                  lt_borr + \
                                  non_cur_liab_due_1y + \
                                  bond_payable + \
                                  int_payable


                 roc = (ebit /magic_cap) if magic_cap !=0 else 0
                 yield_ratio = (ebit / (mkt_val + total_int_liab) )if (mkt_val + total_int_liab ) !=0 else 0
                 ts_df = ts_df.append({'name': ts_code,'roc':roc,'yield_ratio':yield_ratio}, ignore_index=True)
                 #print(income.iloc[-1]['ebit'],balancesheet.iloc[-1]['cap_rese'])
                 #df2 = df2.append(df.iloc[i],ignore_index=True)

         #print("111")
         ts_df['roc_ranked'] = ts_df['roc'].rank(ascending=0,method='min')
         ts_df['yr_ranked'] = ts_df['yield_ratio'].rank(ascending=0, method='min')

         ts_df['sum_rank'] = ts_df['roc_ranked']+ts_df['yr_ranked']
         ts_df['sum_rank'] = ts_df['sum_rank'].rank(ascending=0, method='min')
         ts_df_sorted = ts_df.sort_values(by='sum_rank',ascending=0)

         print ( ts_df_sorted[0:49])




if __name__ == "__main__":
    try:


        main()
        #sys.exit(0)
    except KeyboardInterrupt:
        print("finished.")
    except Exception as err:
        print("Finished with error: ", err)
        raise